import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodList: [
      {
        name: '诸葛亮',
        price: 1000,
        num: 1,
        checked: false
      },
      {
        name: '蔡文姬',
        price: 1500,
        num: 1,
        checked: false
      },
      {
        name: '妲己',
        price: 2000,
        num: 1,
        checked: false
      },
      {
        name: '鲁班',
        price: 2200,
        num: 1,
        checked: false
      }
    ]
  },
  // 修改数据
  mutations: {
    // 加
    addEnd (state, payload) {
      state.goodList[payload].num++
    },
    // 减
    reduce (state, payload) {
      if (state.goodList[payload].num > 1) {
        state.goodList[payload].num--
      } else {
        alert('不能在减了')
      }
    },
    // 全选
    choice (state, payload) {
      return state.goodList.forEach(item => (item.checked = payload))
    },
    // 删除
    deleteObj (state, payload) {
      state.goodList.splice(payload, 1)
    },
    // 添加
    addTo (state, payload) {
      state.goodList.push({
        name: payload.name,
        price: payload.price,
        num: payload.num,
        checked: false
      })
    },
    // 单选
    SelectIt (state, payload) {
      state.goodList[payload[0]] = payload[1]
    }
  },
  getters: {
    // 选中全选选择
    select (state) {
      return state.goodList.every(item => item.checked)
    },
    // 总价
    totalPrice (state) {
      return state.goodList.reduce(function (inValue, dleValue) {
        if (dleValue.checked === true) {
          inValue += dleValue.price * dleValue.num
        }
        return inValue
      }, 0)
    }
  }
})
